package pers.cz.regularexpression;

import org.laziji.commons.rereg.exception.RegexpIllegalException;
import org.laziji.commons.rereg.exception.TypeNotMatchException;
import org.laziji.commons.rereg.exception.UninitializedException;
import org.laziji.commons.rereg.model.Node;
import org.laziji.commons.rereg.model.OrdinaryNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Pattern;

/**
 * 正则表达式工具类
 * @program: PostGirl-panent
 * @description: ExpressionUtils
 * @author: Cheng Zhi
 * @create: 2021-12-18 20:00
 **/
public class ExpressionUtils {

    private static Logger logger = LoggerFactory.getLogger(ExpressionUtils.class);

    /**
     *
     * @param expression
     * @return
     * @throws RegexpIllegalException
     * @throws TypeNotMatchException
     * @throws UninitializedException
     */
    public static String random(String expression)
            throws RegexpIllegalException, TypeNotMatchException, UninitializedException {

        logger.info("正则表达式：" + expression);
        Node node = new OrdinaryNode(expression);
        Pattern pattern = Pattern.compile(node.getExpression());
        String data = node.random();

        return data;
    }

    /**
     * 根据正则表达式生成随机字符
     * @param expression
     * @param title
     * @return
     * @throws RegexpIllegalException
     * @throws TypeNotMatchException
     * @throws UninitializedException
     */
    private static String random(String expression, String title)
            throws RegexpIllegalException, TypeNotMatchException, UninitializedException {

        logger.info("正则表达式：" + expression);
        Node node = new OrdinaryNode(expression);
        Pattern pattern = Pattern.compile(node.getExpression());
        String data = node.random();

        return data;
    }

    public void test() throws RegexpIllegalException, UninitializedException, TypeNotMatchException {

        random("\\w{6,12}@[a-z0-9]{3}\\.(com|cn)", "邮箱");
        random("1(3|5|7|8)\\d{9}", "手机号");
        random("-?[1-9]\\d*\\.\\d+", "浮点数");
        random("https?://[\\w-]+(\\.[\\w-]+){1,2}(/[\\w-]{3,6}){0,2}(\\?[\\w_]{4,6}=[\\w_]{4,6}(&[\\w_]{4,6}=[\\w_]{4,6}){0,2})?", "网址");
    }

    public static void main(String[] args) throws RegexpIllegalException, TypeNotMatchException, UninitializedException {
        String random = random("1(3|5|7|8)\\d{9}");
        System.out.println(random);
    }
}
